package com.mvu.banana.common.widget;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.HasName;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.mvu.banana.common.client.CommonConstants;
import com.mvu.banana.common.shared.CommonDateUtil;
import com.mvu.banana.domain.client.Month;

import java.util.Date;

/**
 * Class description...
 *
 * @author gantz
 */
public class DayBox extends HorizontalPanel implements HasName, HasValue<Date>{
  private String name;

  public ListBox dayBox;
  public EnumBox<Month> monthBox;
  public ListBox yearBox;
  private int minYear;

  public DayBox() {
    super();
    dayBox = new ListBox();
    monthBox = new EnumBox(Month.class);
    yearBox = new ListBox();
    add(dayBox);
    add(monthBox);
    add(yearBox);
    GWTUtil.initListBox(this.dayBox, CommonConstants.get.getString("day"), "0", 1, 31);
    int thisYear = CommonDateUtil.get.getCurrentYear();
    minYear = thisYear - 99;
    GWTUtil.initListBox(this.yearBox, CommonConstants.get.getString("year"), "0", minYear, thisYear);
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getName() {
    return this.name;
  }

  @Override
  public Date getValue() {
    if(dayBox.getSelectedIndex() == 0 || monthBox.getSelectedIndex() == 0
            || monthBox.getSelectedIndex() == 0){
      return null;
    }
    Date date = new Date();
    date.setDate(dayBox.getSelectedIndex());
    date.setMonth(monthBox.getSelectedIndex());
    date.setYear(yearBox.getSelectedIndex());
    return date;
  }

  @Override
  public void setValue(Date value) {
    dayBox.setSelectedIndex(value.getDay());
    monthBox.setSelectedIndex(value.getMonth());
    yearBox.setSelectedIndex(value.getYear() - minYear);
  }

  @Override
  public void setValue(Date value, boolean fireEvents) {
    setValue(value);
    ValueChangeEvent.fire(this, value);
  }

  @Override
  public void removeStyleName(String style){
    monthBox.removeStyleName(style);
    dayBox.removeStyleName(style);
    yearBox.removeStyleName(style);
  }

  @Override
  public void addStyleName(String style){
    monthBox.addStyleName(style);
    dayBox.addStyleName(style);
    yearBox.addStyleName(style);
  }

  @Override
  public HandlerRegistration addValueChangeHandler(ValueChangeHandler<Date> dateValueChangeHandler) {
    return null;
  }
}
